"""
序列化器 基类
"""

from django.db.models import Model
from rest_framework.serializers import (
    DateTimeField,
    IntegerField,
    ModelSerializer,
    Serializer,
)
from rest_framework.views import APIView

from my_typing import *


class BaseTimeSerializer(Serializer):
    """ 时间序列化器 基类 """

    create_time = DateTimeField(label="创建时间")
    update_time = DateTimeField(label="修改时间")


class BasePageQuerySerializer(Serializer):
    """ 分页查询 基类 """

    page = IntegerField(label="页码（第几页）", default=1)
    page_size = IntegerField(label="每页几条", default=10)


def get_serializer(
    view: APIView,
    serializer_cls: type[Serializer],
    *args,
    **kwargs,
) -> Serializer:
    """
    获取 序列化器

    Args:
        view: 视图
        serializer_cls: 序列化器类

    Returns:
        序列化器实例
    """

    if view is not None:
        kwargs.setdefault(
            "context",
            {
                "request": view.request,
                "format": view.format_kwarg,
                "view": view,
            }
        )

    return serializer_cls(*args, **kwargs)


def get_validated_data(
    view: APIView,
    serializer_cls: type[Serializer],
    data: dict,
) -> dict:
    """
    校验数据并获取校验后的数据

    Args:
        view: 视图
        serializer_cls: 序列化器类
        data: 数据

    Returns:
        校验后的数据
    """

    serializer: Serializer = get_serializer(view, serializer_cls, data=data)
    serializer.is_valid(raise_exception=True)

    return serializer.validated_data


def get_validated_data_with_page(
    view,
    serializer_cls: type[Serializer],
    data: dict,
) -> tuple[DictStrAny, DictStrInt]:
    """
    校验数据并获取校验后的数据

    Args:
        view: 视图
        serializer_cls: 序列化器类
        data: 数据

    Returns:
        校验后的数据, 分页查询数据
    """

    validated_data: DictStrAny = {}
    page_query: DictStrInt = {}
    _validated_data: dict = get_validated_data(view, serializer_cls, data)

    for field, value in _validated_data.items():
        if field in BasePageQuerySerializer().get_fields().keys():
            page_query[field] = value

        else:
            validated_data[field] = value

    return validated_data, page_query


def auto_gen_model_serializer(model: type[Model]) -> type:
    """
    动态生成 Model 对应的 ModelSerializer

    Args:
        model: 模型

    Returns:
        ModelSerializer

    >>> class XXXModelSerializer(serializers.ModelSerializer):
    ...     ''' XXX 模型序列化器 '''
    ...
    ...     class Meta:
    ...         model = File
    ...         fields = "__all__"
    """

    sub_class: type = type(
        "Meta",  # ->   类名
        (),  # ->       需要继承的父类
        {  # ->         类的属性（__dict__）
            "model": model,
            "fields": "__all__",
        },
    )
    model_doc: str = str(getattr(model, "__doc__", model.__name__)).strip()  # 移除 2 端空格
    model_serializer: type = type(
        f"{model.__name__}ModelSerializer",
        (ModelSerializer,),
        {
            "Meta": sub_class,
            "__doc__": f" {model_doc} 模型序列化器 ",
        },
    )

    return model_serializer
